<?php

namespace App\Http\Controllers\Api;

use App\Http\Controllers\BaseController;
use App\Models\Cart;
use App\Models\Good;
use App\Transformers\CartTransformer;
use Illuminate\Http\Request;

class CartController extends BaseController
{
    /**
     * 商品列表
     */
    public function index()
    {
        $carts = Cart::where('user_id', auth('api')->id())->with('goods')->get();
        return $this->response->collection($carts, new CartTransformer());
    }

    /**
     * 加入购物车
     */
    public function store(Request $request)
    {
        $request->validate(
            [
                'goods_id' => 'required|exists:goods,id',
                'num'      => [
                    //数量不能超过商品库存
                    function($attribute, $value, $fail) use ($request) {
                        $goods = Good::find($request->goods_id);
                        if ($value > $goods->stock){
                            $fail('数量 不能超过库存');
                        }
                    },
                ],
            ], [
                'goods_id.required' => '商品ID不能为空',
                'goods_id.exists'   => '商品不存在',
            ]
        );

        //查询是否已经加入过购物车
        $cart = Cart::where('user_id', auth('api')->id())->where('goods_id', $request->goods_id)->first();
        if(!empty($cart)){
            $cart->num = $request->input('num', 1);
            $cart->save();
            return $this->response->noContent();
        }

        //加入购物车
        Cart::create(
            [
                'user_id'  => auth('api')->id(),
                'goods_id' => $request->input('goods_id'),
                'num'      => $request->input('num', 1),
            ]
        );
    }

    /**
     * 添加和减少数量
     */
    public function update(Request $request, Cart $cart)
    {
        $request->validate(
            [
                'num' => [
                    'required',
                    'integer',
                    'gte:1',
                    function($attribute, $value, $fail) use ($cart) {
                        if ($value > $cart->goods->stock) {
                            $fail('库存不足');
                        }
                    },
                ],
                [
                    'num.required' => '数量不能为空',
                    'num.integer'  => '数量必须为整数',
                    'num.gte'      => '数量必须大于等于1',
                ],
            ]
        );
        $cart->num = $request->input('num');
        $cart->save();
        return $this->response->noContent();
    }

    /**
     * 移除购物车
     */
    public function destroy(Cart $cart)
    {
        $cart->delete();
        return $this->response->noContent();
    }
}
